import React, { useState, useEffect } from 'react'
import {
  Card,
  Row,
  Col,
  Progress,
  Statistic,
  Typography,
  Space,
  Button,
  Select,
  Table,
  Tag,
  Alert,
  message,
  Descriptions
} from 'antd'
import {
  ReloadOutlined,
  DownloadOutlined,
  SettingOutlined,
  DesktopOutlined,
  DatabaseOutlined,
  HddOutlined,
  ThunderboltOutlined,
  WifiOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'
import systemMonitorService, { 
  SystemMonitorData, 
  ProcessInfo, 
  SystemAlert 
} from '@/services/systemMonitor'

const { Title, Text } = Typography
const { Option } = Select

// 使用从服务导入的接口类型

const Performance: React.FC = () => {
  // 状态管理
  const [metrics, setMetrics] = useState<SystemMonitorData | null>(null)
  const [processes, setProcesses] = useState<ProcessInfo[]>([])
  const [alerts, setAlerts] = useState<SystemAlert[]>([])
  const [loading, setLoading] = useState(false)
  const [autoRefresh, setAutoRefresh] = useState(true)
  const [refreshInterval, setRefreshInterval] = useState(5) // 秒

  // 加载系统监控数据
  const loadSystemData = async () => {
    try {
      setLoading(true)
      
      
      const [systemResponse, processResponse, alertResponse] = await Promise.all([
        systemMonitorService.getSystemOverview(),
        systemMonitorService.getProcessList(20),
        systemMonitorService.getSystemAlerts()
      ])
      
      // 提取data字段 - 数据嵌套在 data.data 中
      const systemData = systemResponse?.data?.data || systemResponse?.data || systemResponse
      const processList = processResponse?.data?.data || processResponse?.data || processResponse
      const alertList = alertResponse?.data?.data || alertResponse?.data || alertResponse
      
      
      setMetrics(systemData)
      setProcesses(Array.isArray(processList) ? processList : [])
      setAlerts(Array.isArray(alertList) ? alertList : [])
    } catch (error) {
      console.error('获取系统监控数据失败:', error)
      
      // 检查是否是认证错误
      if (error.response?.status === 401) {
        message.error('认证失败，请重新登录')
      } else if (error.response?.status === 403) {
        message.error('权限不足')
      } else if (error.code === 'NETWORK_ERROR' || !error.response) {
        message.error('网络连接失败，请检查后端服务是否启动')
      } else {
        message.error(`获取系统监控数据失败: ${error.message || error}`)
      }
    } finally {
      setLoading(false)
    }
  }


  // 获取状态颜色
  const getStatusColor = (usage: number): string => {
    if (usage < 50) return '#52c41a' // 绿色
    if (usage < 80) return '#faad14' // 橙色
    return '#f5222d' // 红色
  }

  // 获取进程状态标签
  const getProcessStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      'Running': { color: 'green', text: '运行中' },
      'Not Responding': { color: 'red', text: '无响应' },
      'Sleeping': { color: 'blue', text: '休眠' },
      'Stopped': { color: 'red', text: '已停止' },
      'Unknown': { color: 'default', text: '未知' }
    }
    const config = statusMap[status] || { color: 'default', text: status }
    return <Tag color={config.color}>{config.text}</Tag>
  }

  // 获取告警类型图标和颜色
  const getAlertConfig = (type: string) => {
    switch (type) {
      case 'error':
        return { color: 'red', icon: <WarningOutlined /> }
      case 'warning':
        return { color: 'orange', icon: <WarningOutlined /> }
      case 'info':
        return { color: 'blue', icon: <InfoCircleOutlined /> }
      default:
        return { color: 'default', icon: <CheckCircleOutlined /> }
    }
  }

  // 进程表格列配置
  const processColumns: ColumnsType<ProcessInfo> = [
    {
      title: 'PID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '进程名',
      dataIndex: 'name',
      key: 'name',
      width: 120
    },
    {
      title: 'CPU (%)',
      dataIndex: 'cpu',
      key: 'cpu',
      width: 100,
      sorter: (a, b) => a.cpu - b.cpu,
      render: (cpu: number) => (
        <Text style={{ color: getStatusColor(cpu) }}>
          {cpu.toFixed(1)}%
        </Text>
      )
    },
    {
      title: '内存 (MB)',
      dataIndex: 'memory',
      key: 'memory',
      width: 120,
      sorter: (a, b) => a.memory - b.memory,
      render: (memory: number) => `${memory} MB`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getProcessStatusTag(status)
    },
    {
      title: '线程数',
      dataIndex: 'threads',
      key: 'threads',
      width: 100
    },
    {
      title: '启动时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150,
      render: (startTime: string) => dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
    }
  ]

  // 加载数据（兼容旧的调用方式）
  const loadData = () => {
    loadSystemData()
  }

  // 格式化时间
  const formatUptime = (days: number): string => {
    const hours = Math.floor((days % 1) * 24)
    const minutes = Math.floor(((days % 1) * 24 % 1) * 60)
    return `${Math.floor(days)}天 ${hours}小时 ${minutes}分钟`
  }

  // 初始化和自动刷新
  useEffect(() => {
    loadSystemData()
  }, [])

  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(loadSystemData, refreshInterval * 1000)
      return () => clearInterval(interval)
    }
  }, [autoRefresh, refreshInterval])

  if (!metrics) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '400px',
        fontSize: '16px'
      }}>
        <Space>
          <ReloadOutlined spin />
          加载系统监控数据中...
        </Space>
      </div>
    )
  }

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Title level={2}>系统性能监控</Title>
        <Space>
          <Select
            value={refreshInterval}
            onChange={setRefreshInterval}
            style={{ width: 120 }}
          >
            <Option value={5}>5秒刷新</Option>
            <Option value={10}>10秒刷新</Option>
            <Option value={30}>30秒刷新</Option>
            <Option value={60}>1分钟刷新</Option>
          </Select>
          <Button
            type={autoRefresh ? 'primary' : 'default'}
            icon={<ThunderboltOutlined />}
            onClick={() => setAutoRefresh(!autoRefresh)}
          >
            {autoRefresh ? '自动刷新' : '手动刷新'}
          </Button>
          <Button icon={<ReloadOutlined />} onClick={loadData} loading={loading}>
            刷新
          </Button>
          <Button icon={<DownloadOutlined />}>
            导出报告
          </Button>
          <Button icon={<SettingOutlined />}>
            设置
          </Button>
        </Space>
      </div>

      {/* 操作系统信息卡片 */}
      <Card title="操作系统信息" style={{ marginBottom: '24px' }}>
        <Descriptions column={4} size="small">
          <Descriptions.Item label="操作系统">{metrics.operatingSystem?.name || '未知'}</Descriptions.Item>
          <Descriptions.Item label="版本">{metrics.operatingSystem?.version || '未知'}</Descriptions.Item>
          <Descriptions.Item label="架构">{metrics.operatingSystem?.architecture || '未知'}</Descriptions.Item>
          <Descriptions.Item label="机器名">{metrics.operatingSystem?.machineName || '未知'}</Descriptions.Item>
          <Descriptions.Item label="用户名">{metrics.operatingSystem?.userName || '未知'}</Descriptions.Item>
          <Descriptions.Item label="域名">{metrics.operatingSystem?.userDomainName || '未知'}</Descriptions.Item>
          <Descriptions.Item label=".NET版本">{metrics.operatingSystem?.dotNetVersion || '未知'}</Descriptions.Item>
          <Descriptions.Item label="CPU名称">{metrics.cpu?.name || '未知'}</Descriptions.Item>
        </Descriptions>
      </Card>

      {/* 系统概览卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="系统运行时间"
              value={formatUptime(metrics.system?.uptime || 0)}
              prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="运行进程"
              value={metrics.system?.processes || 0}
              suffix="个"
              prefix={<DesktopOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="系统线程"
              value={metrics.system?.threads || 0}
              suffix="个"
              prefix={<DatabaseOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均负载"
              value={metrics.system?.loadAverage?.[0]?.toFixed(2) || '0.00'}
              prefix={<ThunderboltOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 性能指标卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* CPU 使用率 */}
        <Col span={6}>
          <Card title={
            <Space>
              <DesktopOutlined />
              <span>CPU 使用率</span>
            </Space>
          }>
            <Progress
              type="circle"
              percent={Math.round(metrics.cpu?.usage || 0)}
              strokeColor={getStatusColor(metrics.cpu?.usage || 0)}
              format={(percent) => `${percent}%`}
            />
            <div style={{ marginTop: '16px' }}>
              <Text type="secondary">核心数: {metrics.cpu?.cores || 0}</Text><br />
              <Text type="secondary">温度: {metrics.cpu?.temperature?.toFixed(1) || '0'}°C</Text><br />
              <Text type="secondary">频率: {metrics.cpu?.frequency?.toFixed(1) || '0.0'} GHz</Text>
            </div>
          </Card>
        </Col>

        {/* 内存使用率 */}
        <Col span={6}>
          <Card title={
            <Space>
              <DatabaseOutlined />
              <span>内存使用率</span>
            </Space>
          }>
            <Progress
              type="circle"
              percent={Math.round(metrics.memory?.usage || 0)}
              strokeColor={getStatusColor(metrics.memory?.usage || 0)}
              format={(percent) => `${percent}%`}
            />
            <div style={{ marginTop: '16px' }}>
              <Text type="secondary">已用: {metrics.memory?.used?.toFixed(1) || '0'} GB</Text><br />
              <Text type="secondary">总计: {metrics.memory?.total?.toFixed(1) || '0'} GB</Text><br />
              <Text type="secondary">可用: {metrics.memory?.available?.toFixed(1) || '0'} GB</Text>
            </div>
          </Card>
        </Col>

        {/* 磁盘使用率 */}
        <Col span={6}>
          <Card title={
            <Space>
              <HddOutlined />
              <span>磁盘使用率</span>
            </Space>
          }>
            <Progress
              type="circle"
              percent={Math.round(metrics.disk?.usage || 0)}
              strokeColor={getStatusColor(metrics.disk?.usage || 0)}
              format={(percent) => `${percent}%`}
            />
            <div style={{ marginTop: '16px' }}>
              <Text type="secondary">已用: {metrics.disk?.used?.toFixed(1) || '0'} GB</Text><br />
              <Text type="secondary">总计: {metrics.disk?.total?.toFixed(1) || '0'} GB</Text><br />
              <Text type="secondary">读取: {metrics.disk?.readSpeed?.toFixed(1) || '0'} MB/s</Text>
            </div>
          </Card>
        </Col>

        {/* 网络状态 */}
        <Col span={6}>
          <Card title={
            <Space>
              <WifiOutlined />
              <span>网络状态</span>
            </Space>
          }>
            <div style={{ textAlign: 'center' }}>
              <div style={{ marginBottom: '16px' }}>
                <Text strong style={{ fontSize: '24px', color: '#1890ff' }}>
                  {metrics.network?.latency?.toFixed(0) || '0'} ms
                </Text>
                <div>延迟</div>
              </div>
              <Text type="secondary">上传: {metrics.network?.uploadSpeed?.toFixed(1) || '0'} MB/s</Text><br />
              <Text type="secondary">下载: {metrics.network?.downloadSpeed?.toFixed(1) || '0'} MB/s</Text><br />
              <Text type="secondary">丢包率: {metrics.network?.packetsLost?.toFixed(2) || '0.00'}%</Text>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 告警信息 */}
      {alerts.filter(alert => !alert.resolved).length > 0 && (
        <Card title="系统告警" style={{ marginBottom: '24px' }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            {alerts.filter(alert => !alert.resolved).map(alert => {
              const config = getAlertConfig(alert.type)
              return (
                <Alert
                  key={alert.id}
                  message={alert.message}
                  description={`时间: ${alert.timestamp}`}
                  type={alert.type}
                  icon={config.icon}
                  showIcon
                  closable
                />
              )
            })}
          </Space>
        </Card>
      )}

      {/* 进程监控 */}
      <Card title="进程监控" style={{ marginBottom: '24px' }}>
        <Table
          columns={processColumns}
          dataSource={processes}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          scroll={{ x: 800 }}
        />
      </Card>

    </div>
  )
}

export default Performance